package controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import Dao.CollectDao;
import Dao.FoodDao;
import Dao.OderDao;
import Dao.ShopDao;
import Dao.TypeDao;
import Dao.UserDao;
import Model.Collect;
import Model.Food;
import Model.Order;
import Model.Shop;
import Model.Type;
import Model.User;
import net.sf.json.JSONObject;

@Controller 
public class FirstController {
	
	@RequestMapping("/register.do")
	public ModelAndView register_b(String nickname,String password,String cellphone) {
		UserDao userDao = new UserDao();
		ModelAndView m = new ModelAndView();
		if (userDao.isExist(nickname)) {
			m.setViewName("reg");
			return m;
		}
		User u = new User();
		u.setUsername(nickname);
		u.setMobilenum(cellphone);
		u.setUserpass(password);
		boolean isOk = userDao.insert(u);
		if(isOk) {
			m.setViewName("login");
		}else {
			m.setViewName("reg");
		}
		return m;
	}
	@RequestMapping("/login.do")
	public ModelAndView login_b(String username,String password) {
		ModelAndView m = new ModelAndView();
		UserDao dao = new UserDao();
		User user = dao.login(username, password);
		if(user != null && user.getUser_id() > 0) {
			ShopDao shopDao = new ShopDao();
			List<Shop> shopList = shopDao.getAll();
			m.addObject("list",shopList);
			m.setViewName("shopList");
			return m;
		}
		m.setViewName("login");
		return m;
	}
	
     //获取数据库当中商铺表的所有记录
	@RequestMapping("/shoplist.do")
	public ModelAndView getAll(){
		//创建一个能够访问到数据库的对象
		ShopDao dao = new ShopDao();
		ArrayList<Shop> list = dao.getAll();
		//需要将数据传输到前端页面
		ModelAndView m = new ModelAndView();
		//将包含数据库tb_shop表所有数据记录的容器对象list放入模型和视图对象m当中
		m.addObject("list",list);
		//确定数据需要返回的页面
		m.setViewName("shopList");
		return m;
	}
	
	//添加一条商铺记录到数据库
	@RequestMapping("/addShop.do")
	public ModelAndView doAddShop(Shop shop) {
		ShopDao dao = new ShopDao();
		dao.insert(shop);
		//因为插入改变了数据库表tb_shop里面的记录数量，需要重新获取
		ArrayList<Shop> list = dao.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("shopList");
		return m;
	}
	//根据页面传递过来的id找寻商铺记录
	@RequestMapping("/findShop.do")
	public ModelAndView doFindShop(int id,HttpSession session) {
		ShopDao dao = new ShopDao();
		Shop shop = dao.getShopById(id);
		ModelAndView m = new ModelAndView();
		m.addObject("shop",shop);
		String path = session.getServletContext().getRealPath("//image");
		File file = new File(path);
		String[] list = file.list();
		m.addObject("list",list);
		m.setViewName("shopupdate");
		return m;
	}
	//根据页面传递过来的修改后的商铺信息去数据库修改指定的数据记录
	@RequestMapping("/updateShop.do")
	public ModelAndView doUpdateShop(Shop shop) {
		ShopDao dao = new ShopDao();
		dao.update(shop);
		ArrayList<Shop> list = dao.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("shopList");
		return m;
	}
	//实现指定的商铺记录的删除
	@RequestMapping("/deleteShop.do")
	public ModelAndView doDeleteShop(int id) {
		ShopDao dao = new ShopDao();
		dao.delete(id);
		ArrayList<Shop> list = dao.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("shopList");
		return m;
	}
	//实现页面上的搜索功能
	@RequestMapping("/search.do")
	public ModelAndView doSearch(String condition,String value) {
		ShopDao dao = new ShopDao();
		ArrayList<Shop> list = dao.getShopsByCondition(condition, value);
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("shopList");
		return m;
	}
	@RequestMapping("/foodlist.do")
	public ModelAndView doGetFoodList() {
		FoodDao dao = new FoodDao();
		ArrayList<Food> list = dao.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("foodList");
		return m;
	}
	@RequestMapping("/createfood.do")
	public ModelAndView doCreateFood(HttpSession session) {
		ShopDao dao = new ShopDao();
		ArrayList<Shop> shoplist = dao.getAll();
		TypeDao dao2 = new TypeDao();
		ArrayList<Type> typelist = dao2.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("shoplist",shoplist);
		m.addObject("typelist",typelist);
		String path = session.getServletContext().getRealPath("//image");
		File images = new File(path);
		String[] list = images.list();
		m.addObject("list",list);
		m.setViewName("food");
		return m;
	}
	@RequestMapping("/addFood.do")
	public ModelAndView doAddFood(Food food) {
		FoodDao dao = new FoodDao();
		dao.insert(food);
		ArrayList<Food> list = dao.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("foodList");
		return m;
	}
	@RequestMapping("/findFood.do")
	public ModelAndView doFindFood(int id,HttpSession session) {
		FoodDao dao1 = new FoodDao();
		Food food = dao1.getFoodById(id);
		ArrayList<Shop> shoplist = new ShopDao().getAll();
		ArrayList<Type> typelist = new TypeDao().getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("food",food);
		m.addObject("shoplist",shoplist);
		m.addObject("typelist",typelist);
		String path = session.getServletContext().getRealPath("//image");
		File file = new File(path);
		String[] list = file.list();
		m.addObject("list",list);
		m.setViewName("foodupdate");
		return m;
	}
	@RequestMapping("/updateFood.do")
	public ModelAndView doUpdateFood(Food food) {
		FoodDao dao = new FoodDao();
		dao.update(food);
		ArrayList<Food> list = dao.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("foodList");
		return m;
	}
	@RequestMapping("/deleteFood.do")
	public ModelAndView doDeleteFood(int id) {
		FoodDao dao = new FoodDao();
		dao.delete(id);
		ArrayList<Food> list = dao.getAll();
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("foodList");
		return m;
	}
	@RequestMapping("/searchFood.do")
	public ModelAndView doSearchFood(String condition,String value) {
		FoodDao dao = new FoodDao();
		ArrayList<Food> list = dao.getFoodByCondition(condition, value);
		ModelAndView m = new ModelAndView();
		m.addObject("list",list);
		m.setViewName("foodList");
		return m;
	}
    @RequestMapping("/userlist.do")
    public ModelAndView getAllUser() {
    	UserDao dao = new UserDao();
    	ArrayList<User>list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("userList");
    	return m;
    }
    @RequestMapping("/addUser.do")
    public ModelAndView doAddUser(User user) {
    	new UserDao().insert(user);
    	ArrayList<User>list = new UserDao().getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("userList");
    	return m;
    }
    @RequestMapping("/findUser.do")
    public ModelAndView doFindUser(int id) {
    	User u =new UserDao().getUserById(id);
    	ModelAndView m = new ModelAndView();
    	m.addObject("user",u);
    	m.setViewName("userupdate");
    	return m;
    }
    @RequestMapping("/updateUser.do")
    public ModelAndView doUpdateUser(User user) {
    	UserDao dao = new UserDao();
    	dao.update(user);
    	ArrayList<User>list = new UserDao().getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("userList");
    	return m;
    }
    @RequestMapping("/deleteUser.do")
    public ModelAndView doDeleteUser(int id) {
    	UserDao dao = new UserDao();
    	dao.delete(id);
    	ArrayList<User>list = new UserDao().getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("userList");
    	return m;
    }
    @RequestMapping("/searchUser.do")
    public ModelAndView doSearchUser(String condition,String value) {
    	UserDao dao = new UserDao();
    	ArrayList<User> list = dao.getUserByCondition(condition, value);
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("userList");
    	return m;
    }
    @RequestMapping("/orderlist.do")
    public ModelAndView doOrderList() {
    	OderDao dao = new OderDao();
    	ArrayList<Order> list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("orderList");
    	return m;
    }
    @RequestMapping("/order.do")
    public ModelAndView doOrder() {
    	UserDao dao1 = new UserDao();
    	ArrayList<User> userlist = dao1.getAll();
    	FoodDao dao2 = new FoodDao();
    	ArrayList<Food> foodlist = dao2.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("userlist",userlist);
    	m.addObject("foodlist",foodlist);
    	m.setViewName("order");
    	return m;
    }
   
    @RequestMapping("/addOrder.do")
    public ModelAndView doAddOrder(Order order) {
    	OderDao dao = new OderDao();
    	dao.insert(order);
    	ArrayList<Order> list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("orderList");
    	return m;
    }
    @RequestMapping("/findOrder.do")
    public ModelAndView doFindOrder(int id) {
    	OderDao dao = new OderDao();
    	Order order = dao.getOrderById(id);
    	ModelAndView m = new ModelAndView();
    	m.addObject("order",order);
    	m.setViewName("orderupdate");
    	return m;
    }
    @RequestMapping("/updateOrder.do")
    public ModelAndView doUpdateOrder(Order order) {
    	OderDao dao = new OderDao();
    	dao.update(order);
    	ArrayList<Order> list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("orderList");
    	return m;
    }
    @RequestMapping("/deleteOrder.do")
    public ModelAndView doDeleteOrder(int id) {
    	OderDao dao =new OderDao();
    	dao.delete(id);
    	ArrayList<Order> list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("orderList");
    	return m;
    }
    @RequestMapping("/searchOrder.do")
    public ModelAndView doSearchOrder(String condition,String value) {
    	OderDao dao = new OderDao();
    	ArrayList<Order> list = dao.getOrderByCondition(condition, value);
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("orderList");
    	return m;
    }
    @RequestMapping("/checkShopName.do")
    public void doCheckShopName(String shopname,HttpServletResponse response) {
    	ShopDao dao = new ShopDao();
    	boolean f = dao.findShopByName(shopname);
    	JSONObject obj = new JSONObject();
    	String msg = "";
    	if(f)msg="该店铺名称已存在";
    	else msg = "该店铺名称不存在";
    	obj.put("msg", msg);
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(obj.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    @RequestMapping("/collectlist.do")
    public ModelAndView doCollectList(){
    	CollectDao dao = new CollectDao();
    	ArrayList<Collect> list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("collectList");
    	return m;
    }
    @RequestMapping("/collectPrepare.do")
    public ModelAndView doCollectPrepare(){
    	ArrayList<User> userlist = new UserDao().getAll();
    	ArrayList<Shop> shoplist = new ShopDao().getAll();
    	ArrayList<Food> foodlist = new FoodDao().getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("userlist",userlist);
    	m.addObject("shoplist",shoplist);
    	m.addObject("foodlist",foodlist);
    	m.setViewName("collect");
    	return m;
    }
    @RequestMapping("/addCollect.do")
    public ModelAndView doAddCollect(Collect c){
    	CollectDao dao = new CollectDao();
    	if(c.getFlag()==0)c.setFood_id(1);
    	else c.setShop_id(1);
    	c.setCollect_date(new Date());
    	dao.insert(c);
    	ArrayList<Collect> list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("collectList");
    	return m;
    }
    @RequestMapping("/deleteCollect.do")
    public ModelAndView doDeleteCollect(int id) {
    	CollectDao dao = new CollectDao();
    	dao.delete(id);
    	ArrayList<Collect> list = dao.getAll();
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("collectList");
    	return m;
    }
    @RequestMapping("/searchCollect.do")
    public ModelAndView  doSearchCollect(String condition,String value) {
    	CollectDao dao = new CollectDao();
    	ArrayList<Collect> list = dao.getCollectByCondition(condition, value);
    
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("collectList");
    	return m;
    }
    @RequestMapping("/listPics.do")
    public ModelAndView doListPics(HttpSession session) {
    	String path = session.getServletContext().getRealPath("\\image");
    	File file = new File(path);
    	String[] list = file.list();
    	
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("uploadImage");
    	return m;
    }
   
    @RequestMapping("/jump.do")
    public ModelAndView doJumpToShopCreate(HttpSession session) {
    	String path = session.getServletContext().getRealPath("\\image");
    	File file = new File(path);
    	String[] list = file.list();
    	
    	ModelAndView m = new ModelAndView();
    	m.addObject("list",list);
    	m.setViewName("shop");
    	return m;
    }
    @RequestMapping("/deletePic.do")
    public ModelAndView doDeletePic(String filename,HttpSession session) {
    	filename = filename.substring(5, filename.length());
    	String path = session.getServletContext().getRealPath("//image");
    	File file = new File(path,filename);
    	 file.delete();
    	 ModelAndView m = new ModelAndView();
    	 m.setViewName("forward:/listPics.do");
    	 return m;
    }
    @RequestMapping("/downloadPic.do")
    public ResponseEntity<byte[]> doDownloadPic(String filename,HttpServletRequest request) {
    	filename = filename.substring(5, filename.length());
    	String path = request.getServletContext().getRealPath("/image/");
    	File file = new File(path,filename);
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentDispositionFormData("attach",filename);
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	try {
			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
    //以下为android端映射
    @RequestMapping("and_getShopList.do")
    public void doGetShopList(HttpServletResponse response) {
    	ShopDao dao = new ShopDao();
    	ArrayList<Shop> list = dao.getAll();
    	String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Shop>>() {}.getType());
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @RequestMapping("and_getFoodsByShopId.do")
    public void doGetFoodsByShopId(int id,HttpServletResponse response) {
    	FoodDao dao = new FoodDao();
    	ArrayList<Food> list = dao.getFoodByShopId(id);
    	String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Food>>() {}.getType());
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @RequestMapping("/and_getFoodByFoodId.do")
    public void doAndGetFoodByFoodId(int id,HttpServletResponse response) {
    	FoodDao dao = new FoodDao();
    	Food food = dao.getFoodById(id);
    	String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(food,Food.class);
    	
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @RequestMapping("/and_getShopByShopId.do")
    public void doAndGetShopByShopId(int id,HttpServletResponse response) {
    	ShopDao dao = new ShopDao();
    	Shop shop = dao.getShopById(id);
    	String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(shop,Shop.class);
    	
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @RequestMapping("/and_getOrderByFoodId.do")
    public void doAndGetOrderByFoodId(int id,HttpServletResponse response) {
    	OderDao dao =new  OderDao();
    	ArrayList<Order> list = dao.getOrderByFoodId(id);
    	String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Order>>() {}.getType());
    	System.out.println("查询菜品评价条数:" + list.size());
    	list.forEach(System.out::println);
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @RequestMapping("/and_getUserByUserId.do")
    public void doAndGetUserByUserId(int id,HttpServletResponse response) {
    	UserDao dao = new UserDao();
    	User user = dao.getUserById(id);
        String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(user,User.class);
    	
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @RequestMapping("/and_addOrder.do")
    public void doAndAddOrder(@RequestBody String s,HttpServletResponse response) {
    	OderDao dao = new OderDao();
    	System.out.println("订单添加请求：" + s);  
    	//使用GsonBuilder转换指定日期格式
    	Order order = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
    			.fromJson(s, Order.class);
    	boolean f = dao.insert(order);
    	JSONObject obj = new JSONObject();
    	String msg = "";
    	if(f)msg = "添加订单成功";
    	else msg = "添加订单失败";
    	obj.put("msg", msg);
    	obj.put("flag", f);
    	response.setCharacterEncoding("UTF-8");
    	try {
			response.getWriter().print(obj.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    	@RequestMapping("/and_addCollect.do")
    	public void doAndAddCollect(@RequestBody String s,HttpServletResponse response) {
    		//s = s.replaceAll("2023", "2023,");
    		Collect c = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(s, Collect.class);
    		CollectDao dao = new CollectDao();
    		boolean f = dao.isExists(c.getUser_id(), c.getShop_id(), c.getFood_id(), c.getFlag());
    		String msg = "";
    		if(f)msg = "已收藏，请勿重复收藏";
    		else {
    		  boolean flag = dao.insert(c);
    		  if(flag)msg = "收藏成功";
    		  else msg = "收藏失败";
    		}
    		JSONObject obj = new JSONObject();
    		obj.put("msg",msg);
    		response.setCharacterEncoding("UTF-8");
    		try {
				response.getWriter().print(obj.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	@RequestMapping("/and_getShopCollect.do")
    	public void doAndGetShopCollect(int id,HttpServletResponse response) {
    		CollectDao dao = new CollectDao();
    		ArrayList<Collect> list = dao.findShopCollect(id);
    		String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Collect>>() {}.getType());
        	System.out.println("该用户收藏的店铺：" + s);
    		response.setCharacterEncoding("UTF-8");
        	try {
    			response.getWriter().print(s);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	@RequestMapping("/and_getFoodCollect.do")
    	public void doAndGetFoodCollect(int id,HttpServletResponse response) {
    		CollectDao dao = new CollectDao();
    		ArrayList<Collect> list = dao.findFoodCollect(id);
    		String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Collect>>() {}.getType());
        	response.setCharacterEncoding("UTF-8");
        	try {
    			response.getWriter().print(s);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	@RequestMapping("/and_deleteCollect.do")
    	public void doAndDeleteCollect(int id,HttpServletResponse response) {
    		new CollectDao().delete(id);
    		JSONObject obj = new JSONObject();
    		obj.put("msg", "");
    		response.setCharacterEncoding("UTF-8");
        	try {
    			response.getWriter().print(obj.toString());
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    		@RequestMapping("/and_getFoodByFoodName.do")
    		public void doAndGetFoodByFoodName(String foodname,HttpServletResponse response) {
    			FoodDao dao = new FoodDao();
    			ArrayList<Food> list = dao.getFoodByCondition("foodname", foodname);
    			String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Food>>() {}.getType());
            	response.setCharacterEncoding("UTF-8");
            	try {
        			response.getWriter().print(s);
        		} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
    		}
    		
    		@RequestMapping("/and_updateUserByUserId.do")
    		public void daoAndUpdateUserByUserId(@RequestBody String s,HttpServletResponse response) {
    				UserDao dao = new UserDao();
    				User user = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(s, User.class);
    				boolean f = dao.updateUserByUserId(user);
    				String msg = "";
    				if(f)msg = "更新成功";
    				else msg = "更新失败";
    				JSONObject obj = new JSONObject();
    				obj.put("msg", msg);
    				response.setCharacterEncoding("UTF-8");
    				try {
						response.getWriter().print(obj.toString());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    			}
    			
    		 @RequestMapping("/and_getShopByFoodId.do")
    		 public void doAndGetShopbyFoodId(int id,HttpServletResponse response) {
    			 ShopDao dao = new ShopDao();
    			 Shop shop = dao.getShopByFoodId(id);
    			 String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(shop,Shop.class);
    			 response.setCharacterEncoding("UTF-8");
 				try {
						response.getWriter().print(s);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    		 }
    		
    			 @RequestMapping("/and_getOrdersByUserId.do")
    			 public void doAndGetOrdersByUserId(int id,HttpServletResponse response) {
    				 OderDao dao = new OderDao();
    				 ArrayList<Order> list = dao.getOrderByUserId(id);
    				 String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Order>>() {}.getType());
    	            	response.setCharacterEncoding("UTF-8");
    	            	try {
    	        			response.getWriter().print(s);
    	        		} catch (IOException e) {
    	        			// TODO Auto-generated catch block
    	        			e.printStackTrace();
    	        		}
    			 }
    			 
    				 @RequestMapping("/and_getPinglunByUserId.do")
    			 public void doAndGetPinglunByUserId(int id,HttpServletResponse response) {
    				 OderDao dao = new OderDao();
    				 ArrayList<Order> list = dao.getOrdersByUserIdCommented(id);
    				 String s = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(list,new TypeToken<ArrayList<Order>>() {}.getType());
    	            	response.setCharacterEncoding("UTF-8");
    	            	try {
    	        			response.getWriter().print(s);
    	        		} catch (IOException e) {
    	        			// TODO Auto-generated catch block
    	        			e.printStackTrace();
    	        		}
    			 }	  
    				 @RequestMapping("/and_updatePinglun.do")
    				public void doAndUpdatePinglun(int id,String content,HttpServletResponse response) {
    					 OderDao dao = new OderDao();
    					 boolean f = dao.updateOrderByOrderId(id, content);
    					 String msg = "";
    					 if(f)msg= "成功";
    					 else msg = "失败";
    					 JSONObject obj = new JSONObject();
    					 obj.put("msg", msg);
    					 response.setCharacterEncoding("UTF-8");
     	            	try {
     	        			response.getWriter().print(obj.toString());
     	        		} catch (IOException e) {
     	        			// TODO Auto-generated catch block
     	        			e.printStackTrace();
     	        		}
    				 }
    				
    		@RequestMapping("/and_deletePinglunById.do")	
    		public void doDeletePinglun(int id,HttpServletResponse response) {
    			OderDao dao = new OderDao();
    			boolean f = dao.deletePinglun(id);
    			String msg = "";
    			 if(f)msg= "删除成功";
				 else msg = "删除失败";
				 JSONObject obj = new JSONObject();
				 obj.put("msg", msg);
				 response.setCharacterEncoding("UTF-8");
	            	try {
	        			response.getWriter().print(obj.toString());
	        		} catch (IOException e) {
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
    		}
    		@RequestMapping("/and_login.do")
    		public void doAndLogin(@RequestBody String s,HttpServletResponse response) {
    			System.out.println("request body :" + s);
    			User user = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(s,User.class);
    			UserDao dao = new UserDao();
    			System.out.println("登陆账号：" + user.getUsername() + "密码：" + user.getUserpass());
    			User u = dao.login(user.getUsername(), user.getUserpass());
    			String msg = "";
    			JSONObject obj = new JSONObject();
    			if(u==null) {
    				msg = "登陆失败";
    				obj.put("msg", msg);
    			}else {
    				msg = "登陆成功";
    				obj.put("msg", msg);
    				obj.put("user_id", u.getUser_id());
    				
    			}
    			response.setCharacterEncoding("UTF-8");
    			try {
					response.getWriter().print(obj.toString());
				} catch (IOException e) {
					e.printStackTrace();
				}
    			
    		}
    		
    		@RequestMapping("/and_register.do")
    		public void doAndRegister(@RequestBody String body,HttpServletResponse res) {
    			System.out.println("request body :" + body);
    			
    			User user = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(body, User.class);
    			JSONObject json = new JSONObject();
    			if(user == null) {
    				json.put("msg", "请求参数错误");
    			}
    			UserDao dao = new UserDao();
    			if(dao.isExist(user.getUsername())){
    				System.out.println("用户已存在");
    				json.put("msg", "用户已存在");
    				json.put("flag", false);
    			}else {
    				boolean reg = dao.register(user.getUsername(), user.getUserpass());
        			json.put("flag", reg);
    			}
    			res.setCharacterEncoding("UTF-8");
    			try {
					res.getWriter().print(json.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    				
   
    		}
    		//允许上传的文件名
    		private static final String[] ALLOWED_IMAGE_EXTENSIONS = {"jpg", "jpeg", "png", "gif", "bmp","webp"};  
    		
    		//上传头像
    		@RequestMapping("/and_upload_advatar.do")
    		public void doAndUploadAdv(@RequestParam("imageFile") MultipartFile file,@RequestParam("userId") String user_Id,HttpServletRequest request,HttpServletResponse res) {
    			 JSONObject json = new JSONObject();
    			 int userId = Integer.parseInt(user_Id);
    			 if (!file.isEmpty() ) {
    				
    		            try {
    		            	
    		            	String pathDir = "uploads\\";
    		                // 获取后缀名 
    		            	String originalFilename = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();; 
    		            	boolean fileIsOk = isAllowedImageExtension(originalFilename);
    		            	//检查文件格式是否合法 和 检查用户id是否存在
    		            	if(!fileIsOk || !new UserDao().isExist(userId)) {
    		            		json.put("flag", false);
            		        	if(fileIsOk) {
            		        		json.put("msg","用户不存在！");
            		        	}else {
            		        		json.put("msg","文件格式不合法！");
            		        	}
            		          	try {
            		        		res.setCharacterEncoding("UTF-8");
            						res.getWriter().print(json.toString());
            					} catch (IOException e) {
            						// TODO Auto-generated catch block
            						e.printStackTrace();
            					} 
            		          	return;
    		            	}
    		            	
    		            	//文件名改为 时间戳_用户id
    		                String fileName = System.currentTimeMillis() + "_" + userId + "." + originalFilename;
    		                
    		                // 设置文件保存的目录，保存到/uploads
    		                String savePath = request.getServletContext().getRealPath("/") + pathDir;
    		     
    		                // 检查并创建目录  
    		                File dir = new File(savePath);  
    		                if (!dir.exists()) {  
    		                    dir.mkdirs();  
    		                } 
    		                System.out.println("上传头像保存文件名：" + fileName);
    		                System.out.println("上传头像保存路径：" + savePath);
    		                Path filePath = Paths.get(savePath, fileName);
    		                // 保存文件  
    		                file.transferTo(filePath.toFile());
    		                //更新数据库
    		                boolean isOk = new UserDao().updateAdvatar(fileName, userId);
    		                if(isOk) {
    		                	json.put("msg", "文件上传成功"); 
    		                }else {
    		                	json.put("msg", "保存失败，请重试"); 
    		                }
    		                json.put("flag", isOk);  
    		                
    		                
    		            } catch (Exception e) {
    		                e.printStackTrace();
    		                json.put("flag", false);
        		        	json.put("msg", e.getMessage());
    		            }
    		        } else {
    		        	json.put("flag", false);
    		        	json.put("msg", "传入文件为空");
    		        
    		    }
    			 
	        	try {
	        		res.setCharacterEncoding("UTF-8");
					res.getWriter().print(json.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
    			 
    			 
    		}
    		//获取头像
    		@RequestMapping("/and_get_advatar.do")
    		public void getUserAdv(int userId,HttpServletResponse res) {
    			JSONObject json = new JSONObject();
    			UserDao dao = new UserDao();
    			if(dao.isExist(userId)) {
    				String adv = dao.getUserAdvById(userId);
    				json.put("flag", true);
		        	json.put("msg", "OK!");
		        	json.put("data", adv);
    			}else {
    				json.put("flag", false);
		        	json.put("msg", "用户不存在");
    			}
    			try {
	        		res.setCharacterEncoding("UTF-8");
					res.getWriter().print(json.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
    		}
    		
    	
    		
    	//检查文件名是否合法	
		 private boolean isAllowedImageExtension(String fileExtension) {  
		        for (String extension : ALLOWED_IMAGE_EXTENSIONS) {  
		            if (extension.equals(fileExtension)) {  
		                return true;  
		            }  
		        }  
		        return false;  
		 }  
    		  
    		
    		
}
